package com.hnist.empdemo.view;

import com.hnist.empdemo.pojo.Department;
import com.hnist.empdemo.pojo.Employee; // 导入员工实体类
import com.hnist.empdemo.pojo.Position;
import com.hnist.empdemo.service.Impl.employServiceImpl;
import com.hnist.empdemo.view.component.*;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.stage.Stage;

import com.hnist.empdemo.utils.PasswordManager;
import com.hnist.empdemo.view.component.EditEmployeeDialog;
import com.hnist.empdemo.utils.FunctionUtils;

import java.util.*;

public class Managementface  {

    private String currentUser;
    // 员工表格（全局定义，方便查询/重置方法操作）
    private TableView<Employee> employeeTable;

    public void setCurrentUser(String username) {
        if (username != null && !username.isEmpty()) {
            this.currentUser = username;
        }
    }

    private PasswordManager passwordManager;
    public void start2(Stage primaryStage) {
        passwordManager = new PasswordManager(currentUser);

        // 1. 顶部标题栏（不变）
        HBox titleBar = new HBox();
        titleBar.setPadding(new Insets(10));
        titleBar.setStyle("-fx-background-color: #666; -fx-text-fill: white;");

        Label titleLabel = new Label("员工信息管理系统");
        titleLabel.setStyle("-fx-font-size: 20px; -fx-text-fill: white;");
        HBox.setHgrow(titleLabel, Priority.ALWAYS);



        // 2. 左侧导航树（不变）
        TreeItem<String> root = new TreeItem<>("Root");
        root.setExpanded(true);

// 一级导航节点：个人中心
        TreeItem<String> personalCenterItem = new TreeItem<>("个人中心");
// 一级导航节点：员工管理（原属于“系统信息”子节点，现在提升为一级）
        TreeItem<String> employeeManageItem = new TreeItem<>("员工管理");
// 一级导航节点：员工信息统计（原属于“数据统计”子节点，现在提升为一级）
        TreeItem<String> employeeStatItem = new TreeItem<>("员工信息统计");

// Root直接添加三个一级节点（删除原有的systemInfoManageItem和dataStatManageItem）
        root.getChildren().addAll(personalCenterItem, employeeManageItem, employeeStatItem);
        TreeView<String> treeView = new TreeView<>(root);
        treeView.setShowRoot(false);
        treeView.setPrefWidth(200);

        // 3. 右侧主要功能区（核心修改：调整布局，新增表格）
        BorderPane rightPanel = new BorderPane();

        // 3.1 上方：查询区域（不变，保持水平居中）
        HBox searchBox = new HBox(10);
        searchBox.setPadding(new Insets(10));
        searchBox.setAlignment(Pos.CENTER_LEFT);
        searchBox.getChildren().add(new Label("请选择左侧功能菜单"));
        rightPanel.setTop(searchBox);

        // 3.2 初始化员工表格（新增：创建表格及列配置）
        initEmployeeTable();
        // 初始化时加载所有员工数据
        List<Employee> allEmployees = employServiceImpl.getInstance().listAllDeptOrPosOrEmpInfo(Employee.class);
        employeeTable.getItems().addAll(allEmployees);

        // 3.3 个人中心面板（不变）
        VBox personalCenterPanel = createPersonalCenterPanel();

        // 3.4 初始中间区域（不变）
        VBox centerBox = new VBox();
        centerBox.setPadding(new Insets(20));
        centerBox.setStyle("-fx-alignment: center;");
        centerBox.getChildren().add(new Label("功能区域 - 请从左侧导航选择操作"));
        rightPanel.setCenter(centerBox);

        // 4. 导航树选择事件（核心修改：员工管理分支新增表格布局）
        treeView.getSelectionModel().selectedItemProperty().addListener((obs, oldVal, newVal) -> {
            if (newVal == null) return;

            String selectedText = newVal.getValue();
            switch (selectedText) {
                case "个人中心":
                    rightPanel.setCenter(personalCenterPanel);
                    searchBox.getChildren().setAll(new Label());
                    break;

                case "员工管理":
                    rightPanel.setTop(searchBox);
                    // 核心：员工管理区域布局 = 查询区域（searchBox） + 表格区域（employeeTable）
                    // 1. 重建查询组件（与之前一致，增加性别下拉框重置）
                    HBox employeeQueryBox = new HBox(15);
                    employeeQueryBox.setPadding(new Insets(5));
                    employeeQueryBox.setAlignment(Pos.CENTER);

                    // 员工编号输入
                    Label idLabel = new Label("员工编号:");
                    TextField idField = new TextField();
                    idField.setPromptText("输入员工编号");
                    idField.setPrefWidth(120);

                    // 员工姓名输入
                    Label nameLabel = new Label("员工姓名:");
                    TextField nameField = new TextField();
                    nameField.setPromptText("输入员工姓名");
                    nameField.setPrefWidth(120);

                    // 性别选择（新增：重置时清空选中）
                    Label genderLabel = new Label("性别:");
                    List<String> genderOptions = Arrays.asList("男", "女");
                    StringComboBox genderComboBox = new StringComboBox(genderOptions);
                    genderComboBox.setPrefWidth(80);

                    // 部门选择
                    Label deptLabel = new Label("部门名称:");
                    List<String> departOptions = employServiceImpl.getInstance().listDistinctDeptOrPos(Department.class);
                    List<Department> departments = new ArrayList<>();
                    departOptions.forEach(departOption ->
                        departments.add(new Department(departOption))
                    );
                    GenericComboBox<Department> departmentComboBox = new GenericComboBox<>(
                            departments, Department::getName
                    );
                    departmentComboBox.setPrefWidth(120);

                    // 职位选择
                    Label jobLabel = new Label("职位名称:");
                    List<String> jobOptions = employServiceImpl.getInstance().listDistinctDeptOrPos(Position.class);
                    List<Position> positions = new ArrayList<>();
                    jobOptions.forEach(jobOption ->
                        positions.add(new Position(jobOption))
                    );
                    GenericComboBox<Position> positionComboBox = new GenericComboBox<>(
                            positions, Position::getName
                    );
                    positionComboBox.setPrefWidth(120);

                    // -------------- 查询按钮逻辑（新增：加载表格数据）--------------
                    Button queryBtn = new Button("查询");
                    queryBtn.setOnAction(e -> {
                        // 构建查询条件
                        Employee queryCondition = new Employee();
                        // 获取输入的查询条件
                        int id = 0;
                        try {
                            String idText = idField.getText().trim();
                            if (!idText.isEmpty()) {
                                id = Integer.parseInt(idText);
                            }
                        } catch (NumberFormatException ex) {
                            // ID格式不正确，忽略ID查询条件
                        }
                        String name = nameField.getText().trim();
                        String gender = genderComboBox.getValue();
                        Department selectedDept = departmentComboBox.getValue();
                        Position selectedPos = positionComboBox.getValue();

                        // 设置查询条件
                        if (id > 0) {
                            queryCondition.setId(id);
                        }
                        if (!name.isEmpty()) {
                            queryCondition.setName(name);
                        }
                        if (gender != null && !gender.isEmpty()) {
                            queryCondition.setGender(gender);
                        }
                        if (selectedDept != null) {
                            queryCondition.setDepartment(selectedDept.getName());
                        }
                        if (selectedPos != null) {
                            queryCondition.setPosition(selectedPos.getName());
                        }

                        // 调用服务查询数据
                        List<Employee> employees = employServiceImpl.getInstance().listAllDeptOrPosOrEmpInfo(Employee.class, queryCondition);

                        // 更新表格数据
                        employeeTable.getItems().clear();
                        employeeTable.getItems().addAll(employees);
                    });

                    // -------------- 重置按钮逻辑（新增：清空表格）--------------
                    Button resetBtn = new Button("重置");
                    resetBtn.setOnAction(e -> {
                        // 1. 清空输入框和下拉框
                        idField.clear();
                        nameField.clear();
                        genderComboBox.getSelectionModel().clearSelection();
                        departmentComboBox.getSelectionModel().clearSelection();
                        positionComboBox.getSelectionModel().clearSelection();

                        // 重置后重新加载所有员工数据
                        List<Employee> employees = employServiceImpl.getInstance().listAllDeptOrPosOrEmpInfo(Employee.class);
                        employeeTable.getItems().clear();
                        employeeTable.getItems().addAll(employees);
                    });

                    // 组装查询组件
                    employeeQueryBox.getChildren().addAll(
                            idLabel, idField,
                            nameLabel, nameField,
                            genderLabel, genderComboBox,
                            deptLabel, departmentComboBox,
                            jobLabel, positionComboBox,
                            queryBtn, resetBtn
                    );
                    searchBox.getChildren().setAll(employeeQueryBox);

                    // 创建功能按钮区域
                    HBox buttonBox = new HBox(10);
                    buttonBox.setPadding(new Insets(5, 0, 5, 0));
                    buttonBox.setAlignment(Pos.CENTER_LEFT);

                    // 创建五个功能按钮
                    Button addBtn = new Button("新增员工");
                    Button editBtn = new Button("编辑员工");
                    Button deleteBtn = new Button("删除员工");
                    Button importBtn = new Button("导入数据");
                    Button exportBtn = new Button("导出数据");

                    // 为按钮添加事件处理（可后续实现具体功能）
                    addBtn.setOnAction(e -> {
                        // 新增员工功能
                        AddEmployeeDialog dialog = new AddEmployeeDialog(primaryStage, employeeTable);
                        dialog.show();
                    });

                    editBtn.setOnAction(e -> {
                        // 编辑员工功能 - 需要先选中表格中的员工记录
                        Employee selectedEmployee = employeeTable.getSelectionModel().getSelectedItem();
                        if (selectedEmployee == null) {
                            showAlert(Alert.AlertType.WARNING, "警告", "请先选择要编辑的员工记录");
                        } else {
                            // 打开编辑员工对话框
                            EditEmployeeDialog dialog = new EditEmployeeDialog(primaryStage, employeeTable, selectedEmployee);
                            dialog.show();
                        }
                    });

                    deleteBtn.setOnAction(e -> {
                        // 删除员工功能 - 需要先选中表格中的员工记录
                        Employee selectedEmployee = employeeTable.getSelectionModel().getSelectedItem();
                        if (selectedEmployee == null) {
                            showAlert(Alert.AlertType.WARNING, "警告", "请先选择要删除的员工记录");
                        } else {
                            // 确认删除对话框
                            Alert confirmAlert = new Alert(Alert.AlertType.CONFIRMATION);
                            confirmAlert.setTitle("确认删除");
                            confirmAlert.setHeaderText(null);
                            confirmAlert.setContentText("确定要删除员工 " + selectedEmployee.getName() + " 吗？");

                            confirmAlert.showAndWait().ifPresent(response -> {
                                if (response == ButtonType.OK) {
                                    // 调用服务删除员工
                                    Boolean result = employServiceImpl.getInstance().deleteEmployeeById(selectedEmployee.getId());
                                    if (result) {
                                        // 删除成功，从表格中移除
                                        employeeTable.getItems().remove(selectedEmployee);
                                        showAlert(Alert.AlertType.INFORMATION, "成功", "员工删除成功");
                                    } else {
                                        showAlert(Alert.AlertType.ERROR, "失败", "员工删除失败");
                                    }
                                }
                            });
                        }
                    });

                    importBtn.setOnAction(e -> {
                        // 创建文件选择对话框实例
                        FileChooserDialog fileDialog = new FileChooserDialog(
                                importBtn.getScene().getWindow(),
                                employeeTable
                        );
                        // 显示导入文件对话框
                        fileDialog.showImportFileDialog();
                    });

                    exportBtn.setOnAction(e -> {
                        // 创建文件选择对话框实例
                        FileChooserDialog fileDialog = new FileChooserDialog(
                                exportBtn.getScene().getWindow(),
                                employeeTable
                        );
                        // 显示导出文件对话框
                        fileDialog.showExportFileDialog();
                    });

                    // 将按钮添加到buttonBox
                    buttonBox.getChildren().addAll(addBtn, editBtn, deleteBtn, importBtn, exportBtn);

                    // 2. 右侧中间区域 = 员工表格（用VBox包裹，设置边距）
                    VBox tableContainer = new VBox(10);
                    tableContainer.setPadding(new Insets(10));

                    // 使用ScrollPane包装表格以支持滚动
                    ScrollPane scrollPane = new ScrollPane();
                    scrollPane.setContent(employeeTable);
                    scrollPane.setFitToWidth(true);  // 自动适应宽度
                    scrollPane.setFitToHeight(true); // 自动适应高度
                    scrollPane.setPrefHeight(600);   // 设置首选高度

                    // 设置表格自适应大小
                    employeeTable.setPrefHeight(600);
                    VBox.setVgrow(scrollPane, Priority.ALWAYS);
                    tableContainer.getChildren().addAll(buttonBox,scrollPane);
                    rightPanel.setCenter(tableContainer);
                    break;

                case "员工信息统计":
                    rightPanel.setTop(null);
                    HBox chartBox = new HBox(50); // 增加间距，避免图表重叠
                    VBox barChartVBox = new VBox();
                    VBox pieChartVBox = new VBox();
                    barChartVBox.setAlignment(Pos.CENTER);
                    pieChartVBox.setAlignment(Pos.CENTER);
                    chartBox.getChildren().addAll(barChartVBox, pieChartVBox);
                    chartBox.setPadding(new Insets(50)); // 减小外间距，让图表更居中
                    chartBox.setAlignment(Pos.CENTER);
                    rightPanel.setCenter(chartBox);

                    // 创建数据（修复数据筛选逻辑，确保所有部门数据都能显示）
                    Map<String, Integer> countEmployees = employServiceImpl.getInstance().countEmployees();
                    List<Map.Entry<String, Number>> data = new ArrayList<>();

                    // 修正数据筛选逻辑，添加所有部门数据（原代码只添加了第4个及以后的数据）
                    for (Map.Entry<String, Integer> entry : countEmployees.entrySet()) {
                        // 过滤掉性别统计数据，只保留部门职位数据
                        if (!"男".equals(entry.getKey()) && !"女".equals(entry.getKey())) {
                            data.add(new AbstractMap.SimpleEntry<>(entry.getKey(), entry.getValue()));
                        }
                    }

                    // 创建柱状图（使用优化后的组件，自动显示数据标签）
                    GenericBarChart<Map.Entry<String, Number>> barChart = new GenericBarChart<>(data);
                    // 添加标题并调整布局
                    Label barChartTitle = new Label("员工人数统计");
                    barChartTitle.setStyle("-fx-font-size: 16px; -fx-font-weight: bold;");
                    barChartVBox.getChildren().setAll(barChartTitle, barChart.getVBox());

                    // 创建饼图（保持不变）
                    int maleCount = countEmployees.getOrDefault("男", 0);
                    int femaleCount = countEmployees.getOrDefault("女", 0);
                    GenderPieChart pieChart = new GenderPieChart(maleCount, femaleCount);
                    Label pieChartTitle = new Label("员工性别比例");
                    pieChartTitle.setStyle("-fx-font-size: 16px; -fx-font-weight: bold;");
                    pieChartVBox.getChildren().setAll(pieChartTitle, pieChart.getVBox());
                    break;
                default:
                    rightPanel.setCenter(centerBox);
                    searchBox.getChildren().setAll(new Label("请选择左侧功能菜单"));
            }
        });

        // 5. 左右分栏 + 整体布局（不变）
        SplitPane splitPane = new SplitPane(treeView, rightPanel);
        splitPane.setDividerPositions(0.2);

        BorderPane mainLayout = new BorderPane();
        mainLayout.setTop(titleBar);
        mainLayout.setCenter(splitPane);

        Scene scene = new Scene(mainLayout, 1300, 800);
        primaryStage.setTitle("员工信息管理系统");
        primaryStage.setScene(scene);

        // 设置全屏模式
        primaryStage.setMaximized(true);
        primaryStage.show();
    }

    /**
     * 新增：初始化员工表格（配置列与员工字段的绑定）
     */
    private void initEmployeeTable() {
        // 1. 创建表格实例
        employeeTable = new TableView<>();
        employeeTable.setStyle("-fx-font-size: 14px;");
        employeeTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); // 列自适应

        // 2. 定义表格列（与Employee字段对应）
        //2.1
        TableColumn<Employee, Double> employeeIDCol = new TableColumn<>("员工ID");
        employeeIDCol.setCellValueFactory(new PropertyValueFactory<>("id"));
        employeeIDCol.setPrefWidth(120);
        // 2.2 员工姓名列
        TableColumn<Employee, String> nameCol = new TableColumn<>("员工姓名");
        nameCol.setCellValueFactory(new PropertyValueFactory<>("name")); // 绑定Employee的getName()
        nameCol.setPrefWidth(120);

        // 2.3 性别列
        TableColumn<Employee, String> genderCol = new TableColumn<>("性别");
        genderCol.setCellValueFactory(new PropertyValueFactory<>("gender"));
        genderCol.setPrefWidth(80);

        // 2.4 部门列（显示部门名称，需绑定Department的name）
        TableColumn<Employee, String> deptCol = new TableColumn<>("部门");
        deptCol.setCellValueFactory(new PropertyValueFactory<>("department"));
        deptCol.setPrefWidth(150);

        // 2.5 职位列（显示职位名称，绑定Position的name）
        TableColumn<Employee, String> posCol = new TableColumn<>("职位");
        posCol.setCellValueFactory(new PropertyValueFactory<>("position"));
        posCol.setPrefWidth(150);

        // 2.6 薪水列（格式化数字，保留2位小数）
        TableColumn<Employee, Double> salaryCol = new TableColumn<>("薪水");
        salaryCol.setCellValueFactory(new PropertyValueFactory<>("salary"));
        salaryCol.setCellFactory(column -> new TableCell<Employee, Double>() {
            @Override
            protected void updateItem(Double salary, boolean empty) {
                super.updateItem(salary, empty);
                if (empty || salary == null) {
                    setText("");
                } else {
                    setText(String.format("%.2f", salary)); // 保留2位小数
                }
            }
        });
        salaryCol.setPrefWidth(120);

        // 3. 将列添加到表格
        employeeTable.getColumns().addAll(employeeIDCol,nameCol, genderCol, deptCol, posCol,salaryCol);
    }

    /**
     * 原有方法：创建个人中心面板（不变）
     */
    private VBox createPersonalCenterPanel() {
        VBox panel = new VBox(20);
        panel.setPadding(new Insets(30));

        VBox infoBox = new VBox(10);
        infoBox.setStyle("-fx-padding: 20; -fx-border-color: #ccc; -fx-border-radius: 5;");
        Label infoTitle = new Label("个人信息");
        infoTitle.setStyle("-fx-font-size: 16px; -fx-font-weight: bold;");
        Label userName = new Label("用户名：" + currentUser);
        Label userRole = new Label("角色：系统管理员");
        infoBox.getChildren().addAll(infoTitle, userName, userRole);

        VBox pwdBox = new VBox(15);
        pwdBox.setStyle("-fx-padding: 20; -fx-border-color: #ccc; -fx-border-radius: 5;");
        Label pwdTitle = new Label("修改密码");
        pwdTitle.setStyle("-fx-font-size: 16px; -fx-font-weight: bold;");

        GridPane pwdGrid = new GridPane();
        pwdGrid.setHgap(10);
        pwdGrid.setVgap(15);

        Label oldPwdLabel = new Label("原密码：");
        PasswordField oldPwdField = new PasswordField();
        oldPwdField.setPrefWidth(200);

        Label newPwdLabel = new Label("新密码：");
        PasswordField newPwdField = new PasswordField();
        newPwdField.setPrefWidth(200);

        Label confirmPwdLabel = new Label("确认新密码：");
        PasswordField confirmPwdField = new PasswordField();
        confirmPwdField.setPrefWidth(200);

        Button confirmBtn = new Button("确认修改");
        confirmBtn.setPrefWidth(200);
        confirmBtn.setOnAction(e -> {
            String oldPassword = oldPwdField.getText();
            String newPassword = newPwdField.getText();
            String confirmNewPassword = confirmPwdField.getText();

            PasswordManager.PasswordChangeResult result =
                    passwordManager.changePassword(oldPassword, newPassword, confirmNewPassword);

            if (result.isSuccess()) {
                showAlert(Alert.AlertType.INFORMATION, "成功", result.getMessage());
                oldPwdField.clear();
                newPwdField.clear();
                confirmPwdField.clear();
            } else {
                if (result.getMessage().contains("原密码")) {
                    showAlert(Alert.AlertType.ERROR, "错误", result.getMessage());
                } else if (result.getMessage().contains("一致")) {
                    showAlert(Alert.AlertType.ERROR, "错误", result.getMessage());
                } else if (result.getMessage().contains("长度") || result.getMessage().contains("字段")) {
                    showAlert(Alert.AlertType.WARNING, "警告", result.getMessage());
                } else {
                    showAlert(Alert.AlertType.ERROR, "失败", result.getMessage());
                }
            }
        });

        pwdGrid.add(oldPwdLabel, 0, 0);
        pwdGrid.add(oldPwdField, 1, 0);
        pwdGrid.add(newPwdLabel, 0, 1);
        pwdGrid.add(newPwdField, 1, 1);
        pwdGrid.add(confirmPwdLabel, 0, 2);
        pwdGrid.add(confirmPwdField, 1, 2);
        pwdGrid.add(confirmBtn, 1, 3);

        pwdBox.getChildren().addAll(pwdTitle, pwdGrid);
        panel.getChildren().addAll(infoBox, pwdBox);
        return panel;
    }

    /**
     * 原有方法：创建占位功能面板（不变）
     */
    private VBox createFunctionPanel(String text) {
        VBox panel = new VBox();
        panel.setPadding(new Insets(20));
        panel.setStyle("-fx-alignment: center; -fx-font-size: 16px;");
        panel.getChildren().add(new Label(text));
        return panel;
    }

    /**
     * 原有方法：显示提示框（不变）
     */
    private void showAlert(Alert.AlertType type, String title, String content) {
        Alert alert = new Alert(type);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }
}